<?php
namespace Jykj\Quicklogin\Controller;

/***************************************************************
 *
 *  Copyright notice
 *
 *  (c) 2015 WHB <wanghongbin@ngoos.org>
 *
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/
require_once(\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('quicklogin') . 'Classes/Lib/saetv2.ex.class.php');
/**
 * The Controller for  Common
 */
class CommonController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController {
   
   /**
     * @var \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface
     * @inject
     */
    protected $persistenceManager;
    
    
   /**
	 * @var \Jykj\Quicklogin\Domain\Repository\FrontendUserRepository
	 * @inject
	 */
	protected $frontendUserRepository=NULL;
	
	
	/**
	 * @var \Jykj\Quicklogin\Domain\Repository\FrontendUserGroupRepository
	 * @inject
	 */
	protected $frontendUserGroupRepository=NULL;
    	
	/**
	 * 绑定
	 */
	public function bindAction(){
		
		$access_token = $this->request->hasArgument('access_token') ? $this->request->getArgument('access_token') : '';
		$openid = $this->request->hasArgument('openid') ? $this->request->getArgument('openid') : '';
		$bind = $this->request->hasArgument('bind') ? $this->request->getArgument('bind') : '';
		$nickname = $this->request->hasArgument('nickname') ? $this->request->getArgument('nickname') : '';
		$groupids = $this->settings['allowedGroups'];
		$usergroups = $this->frontendUserRepository->getGroup($groupids);
		if($openid == ''){
			return new \TYPO3\CMS\Extbase\Error\Error('登录错误, 请重新登录', 1340193849); 
		}
		
		$this->view->assign('openid', $openid);
		$this->view->assign('access_token', $access_token);
		$this->view->assign('bind', $bind);
		$this->view->assign('nickname', $nickname);
		if($this->sitename) $this->view->assign('sitename', $this->sitename);
		$this->view->assign('usergroups',$usergroups);
	}
	
	
	/**
	 * 未绑定的，进行绑定
	 */
	public function bindLoginAction(){
		
		$bind = $this->request->hasArgument('bind') ? $this->request->getArgument('bind') : '';
		if($bind != ''){
			if($user = $this->userlogin($bind['username'],$bind['password'])){
				$userInfo = $this->frontendUserRepository->findByUid($user['uid']);
				if($this->getfrontendUserOpenId($userInfo)){
					$GLOBALS['TYPO3_DB']->exec_DELETEquery('fe_sessions','ses_id="'.$user['ses_id'].'"');
					$this->addFlashMessage('此帐户已被绑定，不能重复绑定');
					$this->redirect('bind',NULL,NULL,array('access_token' => $bind['access_token'], 'openid' => $bind['openid']));
				}else{
					$userInfo = $this->setfrontendUserFiledVlaues($userInfo,$bind);
					$this->frontendUserRepository->update($userInfo);
					$this->persistenceManager->persistAll();
					
					$this->addFlashMessage('绑定成功');
					$this->redirectToSuccessUrl();
				}
			}
			//$this->addFlashMessage('绑定的用户名或密码错误，请重新登录要绑定的账号');
			$this->redirect('bind',NULL,NULL,array('access_token' => $bind['access_token'], 'openid' => $bind['openid']));
		}
		return new \TYPO3\CMS\Extbase\Error\Error('登录错误, 请重新登录', 1340193849); 
	}
	
	
	/**
	 * 未绑定，新用户
	 */
	public function bindRegisterAction(){
        
		$bind = $this->request->hasArgument('bind') ? $this->request->getArgument('bind') : '';
		if($bind != ''){
			if($this->frontendUserRepository->checkFiledIfExist('username', $bind['username'])){
				$this->addFlashMessage('用户名已存在，请重新填写');
				$this->redirect('bind',NULL,NULL,array('access_token' => $bind['access_token'], 'openid' => $bind['openid'],'bind'=>$bind,'from'=>$from));
			}
			if($this->frontendUserRepository->checkFiledIfExist('email', $bind['email'])){
				$this->addFlashMessage('邮箱已存在，请重新填写');
				$this->redirect('bind',NULL,NULL,array('access_token' => $bind['access_token'], 'openid' => $bind['openid'],'bind'=>$bind));
			}
			$userGroup = $this->frontendUserGroupRepository->findByUid($bind['usergroup']);
			$newUser = new \Jykj\Quicklogin\Domain\Model\FrontendUser;
			$newUser->addUsergroup($userGroup);
			$newUser->setUsername($bind['username']);
			$newUser->setPassword($this->getSaltedpaswords($bind['password']));
			$newUser->setName($bind['name']);
			$newUser->setTelephone($bind['telephone']);
			$newUser->setEmail($bind['email']);
			
			$newUser = $this->setfrontendUserFiledVlaues($newUser,$bind);
			$this->frontendUserRepository->add($newUser);
			$this->persistenceManager->persistAll();

			$this->addFlashMessage('绑定成功');
			$this->redirect('login',NULL,NULL,array('fuser' => $newUser));
			
		}
		return new \TYPO3\CMS\Extbase\Error\Error('登录错误, 请重新登录', 1340193849);
	}
    
    
	/**
	 * 登录
	 */
	public function loginAction(\Jykj\Quicklogin\Domain\Model\FrontendUser $fuser){
		
	
		$user = $GLOBALS["TYPO3_DB"]->exec_SELECTgetSingleRow('*','fe_users','uid='.$fuser->getUid()); 
		if($user !== FALSE) {
		
			$GLOBALS["TSFE"]->fe_user->createUserSession($user);
			$GLOBALS["TSFE"]->fe_user->loginSessionStarted = TRUE;
			$GLOBALS["TSFE"]->fe_user->user = $GLOBALS["TSFE"]->fe_user->fetchUserSession();

			$this->addFlashMessage('登录成功');
			$this->redirectToSuccessUrl();
		}else{
			return new \TYPO3\CMS\Extbase\Error\Error('登录错误, 请重新登录', 1340193849); 
		}	
	}
    
    
    /***
	 * 各插件分别设置openid
	 */
	protected function getfrontendUserOpenId(\Jykj\Quicklogin\Domain\Model\FrontendUser $userInfo){
		
		switch($this->request->getControllerName()){
			case 'QQ':
				return $userInfo->getOpenidQq();
				break;
			case 'Wechat':
				return $userInfo->getOpenidWechat();
				break;
			case 'Weibo':
				return $userInfo->getOpenidWeibo();
				break;
		}
	}
    
    
    /**
     * 登录成功跳转页面
     *
     * @return void
     */
    protected function redirectToSuccessUrl(){
        
        if($this->request->hasArgument('from')){
        	//能获取到来源地址，则使用来源地址
            $this->redirectToUri(urldecode($this->request->getArgument('from')), 0, 404);
        }else{
        	$this->redirectToUri(\TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('TYPO3_SITE_URL'));
        }    
    }
	
	/***
	 * 获取各插件openid 及 asscesstooken
	 */
	protected function setfrontendUserFiledVlaues(\Jykj\Quicklogin\Domain\Model\frontendUser $userInfo,$bind){
		$userInfo->setNickname($bind['nickname']);
		switch($this->request->getControllerName()){
			case 'QQ':
				$userInfo->setOpenidQq($bind['openid']);
				$userInfo->setAccessTokenQq($bind['access_token']);
				break;
			case 'Wechat':
				$userInfo->setOpenidWechat($bind['openid']);
				$userInfo->setAccessTokenWechat($bind['access_token']);
				break;
			case 'Weibo':
				$userInfo->setOpenidWeibo($bind['openid']);
				$userInfo->setAccessTokenWeibo($bind['access_token']);
				break;
		}
		return $userInfo;	
	}
    
	
	/**
	 * 获取远程页面内容
	 */
	protected function get_contents($url,$method="GET"){
		
		$ch = curl_init();
		
		if($method == 'POST') curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_URL, $url);
		$response =  curl_exec($ch);
		curl_close($ch);
        
		return $response;
	}
	
	
	/**
	 * 用户登录
	 * @param string $username //用户名、手机、邮箱
	 * @param string $password
	 * @return array 
	 */
	protected function userlogin($account,$password) {
		
		$GLOBALS['TSFE']->fe_user->checkPid = FALSE;
		$GLOBALS['TSFE']->fe_user->dontSetCookie = TRUE;
		
		// process login
		$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
			'*',
			'fe_users',
			'disable = 0  AND  deleted = 0 AND username="'.trim($account).'"'
		);
		

		if(!$GLOBALS['TYPO3_DB']->sql_error()) {
			
			while ($user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
				
				$saltedPassword =  $user['password'];  // salted user password hash
				$success = FALSE; // keeps status if plain-text password matches given salted user password hash
				if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('saltedpasswords') && \TYPO3\CMS\Saltedpasswords\Utility\SaltedPasswordsUtility::isUsageEnabled('FE')) {
					$objSalt = \TYPO3\CMS\Saltedpasswords\Salt\SaltFactory::getSaltingInstance(NULL);
					if (is_object($objSalt)) {
						$success = $objSalt->checkPassword($password, $saltedPassword);
					}
				}elseif($password == $user['password']) { //no saltedpaswords
					$success = TRUE;
				}
        
				if($success) {
					$GLOBALS['TSFE']->fe_user->createUserSession($user);
					$GLOBALS['TSFE']->fe_user->loginSessionStarted = TRUE;
					$GLOBALS['TSFE']->fe_user->user = $GLOBALS['TSFE']->fe_user->fetchUserSession();
					return $GLOBALS['TSFE']->fe_user->user;
				}
			}
			$GLOBALS['TYPO3_DB']->sql_free_result($res);
			
			$this->addFlashMessage('绑定的用户名或密码错误，请重新登录要绑定的账号');
			return false;
		}
		
		$this->addFlashMessage('绑定错误，请重试');
		return false;
	}
    
    
    /**
	 * 获取加密后的密码
	 * @param string $password
	 * @return string
	 */
	protected function getSaltedpaswords($password){
		
		if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('saltedpasswords') && \TYPO3\CMS\Saltedpasswords\Utility\SaltedPasswordsUtility::isUsageEnabled('FE')) {
			$objSalt = \TYPO3\CMS\Saltedpasswords\Salt\SaltFactory::getSaltingInstance(NULL);
			if (is_object($objSalt)) {
				return $objSalt->getHashedPassword($password);
			}
		}
		
		return $password;
	}
	
	public function get_pure_url($url)
    {
        $newUrl = strstr("$url","?",true);
        return $newUrl;
    }

	/**
     * 发送邮件
     * @param array $receiver
	 * @param string $subject
     * @param string $body
     * //$mail->setTo(array($email => $name));
     * //$mail->setFrom(array($email => $name));
     * return void
     */
    protected function sendmail($receiver,$subject,$body){

        $mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
        $mail->setFrom(\TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom());
        $mail->setTo($receiver);
        $mail->setSubject($subject);
        $mail->setBody($body,'text/html');
        return $mail->send();
    }
	
	
	/**
	 * 添加通知
	 * @param int $sender 发送人 用户UID
	 * @param int $reciver 接收人 用户UID
	 * @param string $content  通知内容
	 * @return boolean  发送状态 
	 */
	protected function sendMessage($sender,$reciver,$content){
		
		if(\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('vlmgr_notification')){
			return \tx_vlmgrnotification_pi1::createNotification('mfwc_sociallogin',$sender,$reciver,$content);
		}
	}
}